<?php


namespace app\reception\logic;


use app\common\model\Banner;
use app\common\model\ExamineNovel;
use app\common\model\Novel;
use app\common\model\DefaultBookshelf;
use app\common\model\QuickOpen;
use app\common\model\RechargeActivity;
use app\common\model\RechargeItem;
use app\common\model\Recommend;
use app\common\model\RecommendNovel;
use app\reception\server\ContentServer;
use think\Db;
use think\db\Expression;

class PageLogic
{

    /**
     * banner
     * @param $user
     * @param $where
     * @return \think\response\Json
     */
    public function getBanner($user, $where)
    {
        $cache = false;
        $banners = Banner::where($where)->field('content_type,banner,novel_id,activity_id')->cache($cache)->select()->toArray();
        $novelIds = array_column($banners, 'novel_id');
        $activityIds = array_column($banners, 'activity_id');

        /**
         * 条件：上架、专属判断
         */
        $novelWhere[] = ['id', 'in', $novelIds];
        $novelWhere[] = ['in_shelf', '=', 1];
        $filed = "id novel_id,origin_title novel_title";
        $bannerNovels = Novel::field($filed)
            ->where($novelWhere)
            ->cache($cache)
            ->select()->toArray();
        $bannerNovels = array_column($bannerNovels, null, 'novel_id');
        $existActivityIds = RechargeActivity::where('id', 'in', $activityIds)->cache($cache)->column('id');

        foreach ($banners as $k => $v) {
            $banners[$k]['banner'] = config('img_domain') . $v['banner'];
            if ($v['content_type'] == 1) {
                if (!isset($bannerNovels[$v['novel_id']])) {
                    unset($banners[$k]);
                }
            }
            if ($v['content_type'] == 2) {
                if (!in_array($v['activity_id'], $existActivityIds)) {
                    unset($banners[$k]);
                }
            }
        }
        return sucJson($banners);
    }

    /**
     * 获取推荐位
     * @param $user
     * @param $type
     * @return \think\response\Json
     * @Author: whh
     */
    public function getRecommendNovels($user, $type)
    {
        $cache = 6000;
        $location_key = input('location_key');
        $page = input('page');
        $limit = input('limit');

        $where[] = ['quick_id', '=', $user->quick_id];
        $where[] = ['location_key', '=', $location_key];
        $recommend = Recommend::where($where)->cache($cache)->find();
        if (!$recommend){
            return errJson('推荐位不存在');
        }
        $isRandom = $recommend['is_random'];
        if ($type == 1 || $type == 2) {
            $isRandom = $recommend['is_random'];
            $rWhere[] = ['rid', '=', $recommend['id']];
            $rWhere[] = ['type', '=', $type];
            $novelIds = RecommendNovel::where($rWhere)->order("sort asc,id desc")->cache($cache)->column('novel_id');
        } else {
            $novelIds = ExamineNovel::where('quick_id',$user->quick_id)->cache($cache)->column('novel_id');
        }
        /**条件上架*/
        $novelWhere[] = ['id', 'in', $novelIds];
        $novelWhere[] = ['in_shelf', '=', 1];

        /**如果带上分页，就强制按顺序展示*/
        if ($page) {
            $isRandom = 0;
        }

        $filed = "id novel_id,cover,origin_title novel_title,author,freq_id,class_id,update_status,brief,number_words";
        $query = Novel::field($filed)->where($novelWhere);
        if ($isRandom == 1) {
            $query = $query->orderRand();
        } else {
            $orderBy = '';
            if ($novelIds) {
                $orderBy = new Expression('field(id,' . implode(',', $novelIds) . ')');
            }
            $query = $query->order($orderBy)->cache($cache);//不随机就可以查缓存了
        }
        if ($page) {
            $count = Novel::where($novelWhere)->cache($cache)->count();
            $list = $query->page($page, $limit)->select();
        } else {
            $list = $query->limit($limit)->select();
        }
        foreach ($list as $k => $novel) {
            $list[$k]['number_words_text'] = $novel->number_words_text;
        }
        $list = $list->toArray();
        $cidArr = array_column($list, 'class_id');
        $fidArr = array_column($list, 'freq_id');
        $classList = ContentServer::plGetNovelClass($cidArr);
        $freqList = ContentServer::plGetNovelFreq($fidArr);
        foreach ($list as $k => $v) {
            $list[$k]['cover'] = config('img_domain') . $v['cover'];
            $list[$k]['freq'] = isset($freqList[$v['freq_id']]) ? $freqList[$v['freq_id']] : '';
            $list[$k]['novel_class'] = isset($classList[$v['class_id']]) ? $classList[$v['class_id']] : '';
        }
        $data['title'] = $recommend['title'];
        $data['list'] = $list;
        if ($page) {
            $data['count'] = $count;
            return sucJson($data);
        } else {
            return sucJson($data);
        }
    }


    public function getBatchRecommendNovels($user, $type)
    {
        $cache = 6000;
        $location_keys = input('location_keys');
        $limits = input('limits');
        $location_keys = explode(',', $location_keys);
        $limits = explode(',', $limits);
        if (count($location_keys) != count($limits)) {
            return errJson('location_keys和limits数量必须一致');
        }
        $ListData = [];
        foreach ($location_keys as $k => $location_key) {
            $limit = $limits[$k];
            $where = [];
            $where[] = ['quick_id', '=', $user->quick_id];
            $where[] = ['location_key', '=', $location_key];
            $recommend = Recommend::where($where)->cache($cache)->find();
            if (!$recommend) {
                $ListData[$location_key] = '推荐位不存在';
                continue;
            }
            $isRandom = $recommend['is_random'];
            if ($type == 1 || $type == 2) {
                $isRandom = $recommend['is_random'];
                $rWhere = [];
                $rWhere[] = ['rid', '=', $recommend['id']];
                $rWhere[] = ['type', '=', $type];
                $novelIds = RecommendNovel::where($rWhere)->order("sort asc,id desc")->cache($cache)->column('novel_id');
            } else {
                $novelIds = ExamineNovel::where('quick_id',$user->quick_id)->cache($cache)->column('novel_id');
            }
            /**条件上架*/
            $novelWhere = [];
            $novelWhere[] = ['id', 'in', $novelIds];
            $novelWhere[] = ['in_shelf', '=', 1];

            $filed = "id novel_id,cover,origin_title novel_title,author,freq_id,class_id,update_status,brief,number_words";
            $query = Novel::field($filed)->where($novelWhere);
            if ($isRandom == 1) {
                $query = $query->orderRand();
            } else {
                $orderBy = '';
                if ($novelIds) {
                    $orderBy = new Expression('field(id,' . implode(',', $novelIds) . ')');
                }
                $query = $query->order($orderBy)->cache($cache);//不随机就可以查缓存了
            }
            $list = $query->limit($limit)->select();

            foreach ($list as $k => $novel) {
                $list[$k]['number_words_text'] = $novel->number_words_text;
            }
            $list = $list->toArray();
            $cidArr = array_column($list, 'class_id');
            $fidArr = array_column($list, 'freq_id');
            $classList = ContentServer::plGetNovelClass($cidArr);
            $freqList = ContentServer::plGetNovelFreq($fidArr);
            foreach ($list as $k => $v) {
                $list[$k]['cover'] = config('img_domain') . $v['cover'];
                $list[$k]['freq'] = isset($freqList[$v['freq_id']]) ? $freqList[$v['freq_id']] : '';
                $list[$k]['novel_class'] = isset($classList[$v['class_id']]) ? $classList[$v['class_id']] : '';
            }
            $ListData[$location_key]['title'] = $recommend['title'];
            $ListData[$location_key]['list'] = $list;
        }
        return sucJson($ListData);
    }

    /**
     * 充值项列表
     * @param $user
     * @param $where
     * @param $templateId
     * @param $qid
     * @return array|array[]|\array[][]
     */
    public function getRechargeItems($user, $where, $templateId, $qid)
    {
        /**
         * 如果充值过，首充不展示
         */
        if ($user->pay_times > 0) {
            $where[] = ['first', '=', 0];
        }
        $orderBy = "sort asc,id asc";
        $field = "id,total_fee,virtual_currency,point_gift,vipdays,selected,lable,lable_open,desc";
        if (!$templateId){
            $list = RechargeItem::field($field)->where($where)->where("manage_id", 0)->where("quick_id", $qid)->order($orderBy)->select()->toArray();
        }else{
            $list = RechargeItem::field($field)->where($where)->where("template_id", $templateId)->order($orderBy)->select()->toArray();
            if (!$list){
                $list = RechargeItem::field($field)->where($where)->where("manage_id", 0)->where("quick_id", $qid)->order($orderBy)->select()->toArray();
            }
        }
        $selected = 0;
        foreach ($list as $k => $v) {
            if ($selected == 0) {
                if ($v['selected'] == 1) {
                    $selected = 1;
                }
            } else {
                if ($v['selected'] == 1) {
                    $list[$k]['selected'] = 0;
                }
            }
            if ($v['desc'] == ''){
                if ($v['virtual_currency'] != 0){
                    $list[$k]['desc'] = $v['virtual_currency'] . '书币+' . $v['point_gift'] . '书点';
                }else{
                    $list[$k]['desc'] = $v['vipdays'].'天会员';
                }
            }
        }
        if ($selected == 0 && $list) {
            $list[0]['selected'] = 1;
        }
        return $list;
    }


    /**
     * 阅读页下方书籍
     * @param $user
     * @param $where
     * @return \think\response\Json
     */
    public function getReadBelowNovels($user, $where)
    {
        $cache = 600;
        $nIds = DefaultBookshelf::where($where)->order("sort asc,id desc")->cache($cache)->column("novel_id");
        /**条件上架*/
        $novelWhere[] = ['id', 'in', $nIds];
        $novelWhere[] = ['in_shelf', '=', 1];
        $filed = "id novel_id,cover,origin_title novel_title,author,freq_id,class_id,update_status,chapter_up_time,brief";
        $novels = Novel::field($filed)
            ->where($novelWhere)
            ->orderRand()->limit(4)
            ->select()->toArray();

        $cidArr = array_column($novels, 'class_id');
        $fidArr = array_column($novels, 'freq_id');
        $classList = ContentServer::plGetNovelClass($cidArr);
        $freqList = ContentServer::plGetNovelFreq($fidArr);

        foreach ($novels as $k => $v) {
            $novels[$k]['cover'] = config('img_domain') . $v['cover'];
            $novels[$k]['freq'] = isset($freqList[$v['freq_id']]) ? $freqList[$v['freq_id']] : '';
            $novels[$k]['novel_class'] = isset($classList[$v['class_id']]) ? $classList[$v['class_id']] : '';
        }
        return sucJson($novels);
    }




    public function getOpenFace($user){
        /**快应用*/
        $where = [];
        $where[] = ['', 'exp', Db::raw("FIND_IN_SET($user->quick_id,quick_apps)")];
        /**用户群体*/

        if (ipUnblocked($user)) {
            $where[] = ['user_grep', 'in', [1, 0]];
        } else {
            $where[] = ['user_grep', 'in', [2, 0]];
        }
        QuickOpen::where($where)->where(function ($query) use ($user){
            $query->where();

        });
        $query = $list = QuickOpen::where($where)->whereOr();
        $face = $query->order("wgt desc,id desc")->find();
        print_r($face);
    }
}